package dhy.com.server;

import dhy.com.config.protocol.MessageCodecSharable;
import dhy.com.config.protocol.ProcotolFrameDecoder;
import dhy.com.server.handler.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelDuplexHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * <p>
 *     聊天服务器
 * </p>
 * @author zdh
 */
@Slf4j
public class ChatServer {
    public static void main(String[] args)
    {
        //负责处理连接的线程
        NioEventLoopGroup boss = new NioEventLoopGroup();
        //负责处理读写事件的线程
        NioEventLoopGroup worker = new NioEventLoopGroup();

        //下面抽出成局部变量的都是线程安全的处理器
        //日志处理器
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        //自定义消息编解码处理器----通过我们自己规定的协议,完成通信
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        //继承SimpleChannelInboundHandler,只负责处理登录消息
        LoginRequestMessageHandler LOGIN_HANDLER = new LoginRequestMessageHandler();
        //继承SimpleChannelInboundHandler,只负责处理私聊消息
        ChatRequestMessageHandler CHAT_HANDLER = new ChatRequestMessageHandler();
        //继承SimpleChannelInboundHandler,只负责处理群聊创建消息
        GroupCreateRequestMessageHandler GROUP_CREATE_HANDLER = new GroupCreateRequestMessageHandler();
        //继承SimpleChannelInboundHandler,只负责处理加入群聊消息
        GroupJoinRequestMessageHandler GROUP_JOIN_HANDLER = new GroupJoinRequestMessageHandler();
        //继承SimpleChannelInboundHandler,只负责处理拉入群聊消息
        GroupMembersRequestMessageHandler GROUP_MEMBERS_HANDLER = new GroupMembersRequestMessageHandler();
        //继承SimpleChannelInboundHandler,只负责处理退群消息
        GroupQuitRequestMessageHandler GROUP_QUIT_HANDLER = new GroupQuitRequestMessageHandler();
        //继承SimpleChannelInboundHandler,只负责处理群发消息
        GroupChatRequestMessageHandler GROUP_CHAT_HANDLER = new GroupChatRequestMessageHandler();
        //监听客户端断开连接事件
        QuitHandler QUIT_HANDLER = new QuitHandler();

        try {
            //启动器
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.group(boss, worker);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                //建立连接时触发
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    //添加包装后的帧解码器ProcotolFrameDecoder extends LengthFieldBasedFrameDecoder
                    //防止半包问题
                    ch.pipeline().addLast(new ProcotolFrameDecoder());
                     //日志处理器
                   // ch.pipeline().addLast(LOGGING_HANDLER);
                    //对消息进行编解码处理
                    ch.pipeline().addLast(MESSAGE_CODEC);
                    //处理客户端假死情况:
                    // 用来判断是不是 读空闲时间过长，或 写空闲时间过长
                    // 5s 内如果没有收到 channel 的数据，会触发一个 IdleState#READER_IDLE 事件
                    ch.pipeline().addLast(new IdleStateHandler(5, 0, 0));
                    // ChannelDuplexHandler 可以同时作为入站和出站处理器
                    ch.pipeline().addLast(new ChannelDuplexHandler() {
                        // 用来触发特殊事件
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception{
                            IdleStateEvent event = (IdleStateEvent) evt;
                            // 触发了读空闲事件
                            if (event.state() == IdleState.READER_IDLE) {
                                log.debug("已经 5s 没有读到数据了");
                                ctx.channel().close();
                            }
                        }
                    });
                    //登录处理器
                    ch.pipeline().addLast(LOGIN_HANDLER);
                    //私聊处理器
                    ch.pipeline().addLast(CHAT_HANDLER);
                    //建群处理器
                    ch.pipeline().addLast(GROUP_CREATE_HANDLER);
                    //加群处理器
                    ch.pipeline().addLast(GROUP_JOIN_HANDLER);
                    //拉群处理器
                    ch.pipeline().addLast(GROUP_MEMBERS_HANDLER);
                    //退群处理器
                    ch.pipeline().addLast(GROUP_QUIT_HANDLER);
                    //群聊处理器
                    ch.pipeline().addLast(GROUP_CHAT_HANDLER);
                    //监听客户端断开连接事件
                    ch.pipeline().addLast(QUIT_HANDLER);
                }
            });
            //启动服务器--sync()同步等待直到启动成功
            Channel channel = serverBootstrap.bind(8080).sync().channel();
            //监听服务器关闭事件---sync()同步等待，直到事件发生
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("server error", e);
        } finally {
            //关闭额外的工作线程
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }

}
